# coding=utf-8
# 全世界最帅的帅哥
import pymysql
from ysgg1_club_comment.modules.subject_liked import SubjectLiked
from ysgg1_club_subject.constant.redis_prefix import RedisPrefix
from ysgg1_club_subject.redis_client import redis_liked_client
from ysgg1_club_celery.utils.test_utils import get_hash_and_delete
from ysgg1_club_celery.celery_app import celery_app
from ysgg1_club_celery.modules import db


@celery_app.task
def sync_liked():
    """
    扫描 Redis 中的点赞数据，并同步到 MySQL。
    """
    try:
        # 从 Redis 中获取并删除点赞数据
        subject_liked_map = get_hash_and_delete(redis_liked_client, RedisPrefix.SUBJECT_LIKED_KEY)
        if not subject_liked_map:
            return "没有需要同步的数据"

        # 将 Redis 数据转换为数据库对象
        subject_liked_list = []
        for key, val in subject_liked_map.items():
            key_str = key.decode('utf-8')
            val_str = val.decode('utf-8')
            subject_id, like_user_id = key_str.split(':')

            subject_liked = SubjectLiked(
                subject_id=int(subject_id),
                like_user_id=like_user_id,
                status=int(val_str),
                is_delete=0  # 假设未删除
            )
            subject_liked_list.append(subject_liked)

        # 批量插入或更新到数据库
        db.session.bulk_save_objects(subject_liked_list)
        db.session.commit()

        return "数据同步成功"
    except Exception as e:
        db.session.rollback()
        return f"数据同步失败: {str(e)}"




